<template>
  <div class="productsmam">
    <a-card title="产品管理">
      <a-tabs v-model="form.status" @change="callback">
        <a-tab-pane key="1" tab="全部"> </a-tab-pane>
        <a-tab-pane key="2" tab="活动中"> </a-tab-pane>
        <a-tab-pane key="3" tab="即将到期"> </a-tab-pane>
        <a-tab-pane key="4" tab="已暂停"> </a-tab-pane>
        <a-tab-pane key="5" tab="已下架"> </a-tab-pane>
      </a-tabs>
      <div class="search_box">
        <div class="search_left">
          <a-input v-model="form.item_id" style="width:270px" placeholder="请输入淘宝产品ID" />
          <a-range-picker
            :ranges="{ 今天: [moment(), moment()], 本月: [moment(), moment().endOf('month')] }"
            show-time
            v-model="timearr"
            format="YYYY/MM/DD HH:mm:ss"
            @change="onChange"
          />
          <a-input v-model="form.search" style="width:300px" placeholder="请输入产品名称" />
          <!-- <a-input v-model="form.item_id" style="width:300px" placeholder="请输入发布人" /> -->
          <a-select v-model="form.goods_status" style="width: 120px" v-show="form.status == '1'" @change="selectchange">
            <a-select-option value="1">
              活动中
            </a-select-option>
            <a-select-option value="2">
              即将到期
            </a-select-option>
            <a-select-option value="3">
              已暂停
            </a-select-option>
            <a-select-option value="4">
              已下架
            </a-select-option>
          </a-select>
          <div>
            <a-button @click="getGoodsInfo">查询 </a-button> &nbsp;
            <a-button @click="doclear">重 置 </a-button>
          </div>
        </div>
        <div class="btns">
          <!-- <a-button icon="plus" style="background: #2db7f5;color: white;">
            发布
          </a-button>&nbsp; -->
          <a-button icon="edit" style="background: #13c2c2;color: white;" @click="open"> 修改 </a-button>&nbsp;
          <a-button icon="vertical-align-bottom" @click="shelfGoods"> 下架 </a-button>&nbsp;
          <!-- <a-button icon="vertical-align-top" type="primary">
            上架
          </a-button>&nbsp; -->
          <a-button icon="vertical-align-middle" style="background: orange;color: white;" @click="stopGoods">
            暂停 </a-button
          >&nbsp;
          <a-button icon="upload" style="background: #2db7f5;color: white;">
            导出
          </a-button>
        </div>
      </div>
      <a-table
        :columns="columns"
        :row-key="record => record.id"
        :data-source="data"
        :pagination="pagination"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="goods_img" slot-scope="record">
          <img
            :src="record.goods_img"
            alt=""
            srcset=""
            style="width:120px;"
          /></template>
        <template slot="goods_title" slot-scope="record">
          <a :href="record.goods_url" target="_blank" rel="noopener noreferrer">{{ record.goods_title }}</a></template
        >
        <template slot="price" slot-scope="record">
          {{ record.price }}/{{ record.after_price }}/{{ record.zk_price }}</template
        >
        <template slot="service" slot-scope="record"> {{ record.service }}%</template>
        <template slot="goods_type" slot-scope="record">
          <span style="background-color:blue;color:white;padding:2px 5px;">{{ record.typename }}</span>
        </template>
        <template slot="status" slot-scope="record">
          <a-tag
            :color="
              record.status == 1
                ? 'gray'
                : record.status === 2
                  ? 'cyan'
                  : record.status === 3
                    ? 'green'
                    : record.status === 4
                      ? 'orange'
                      : 'red'
            "
          >
            {{
              record.status == 1
                ? '审核中 '
                : record.status === 2
                  ? '待审核'
                  : record.status === 3
                    ? '活动中'
                    : record.status === 4
                      ? '已暂停'
                      : '已下架'
            }}
          </a-tag>
        </template>
        <template slot="coupon_surplus" slot-scope="record">
          <div><a :href="record.coupon_url" target="_blank" rel="noopener noreferrer">领取</a></div>
          <div>{{ record.coupon_surplus }}/{{ record.coupon_num }}</div>
        </template>
        <template slot="active" slot-scope="record">
          <a-button icon="edit" text @click="open(record)"> 修改 </a-button>
        </template>
      </a-table>
      <a-modal
        title="修改商品"
        :visible="editgoods"
        width="1200px"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form-model ref="ruleForm" :model="form2" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="推广标题(精简12字以内)" prop="tg_title">
            <a-input v-model="form2.tg_title" />
          </a-form-model-item>
          <a-form-model-item label="产品分类" prop="goods_class">
            <a-select v-model="form2.goods_class" placeholder="请选择分类">
              <a-select-option :value="item.id" v-for="(item, index) in classList" :key="index">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="商品图片" prop="goods_img">
            <a-input v-model="form2.goods_img" placeholder="请输入商品图片地址或自行上传" />
            <a-upload
              v-if="form2.goods_img == ''"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadurl"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <div>
                <a-icon :type="uploadloading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
            <div v-else class="img_box">
              <img :src="form2.goods_img" alt="" style="width:150px" />
              <a-icon type="close-circle" @click="closeimg" />
            </div>
          </a-form-model-item>
          <a-form-model-item label="朋友圈文案" prop="friend_text">
            <editor-bar v-model="form2.friend_text" @change="getEditor" id="weditor"> </editor-bar>
          </a-form-model-item>
          <a-form-model-item label="结束时间" prop="activity_end_time">
            <a-date-picker v-model="end_time" format="YYYY-MM-DD" @change="endChange" />
          </a-form-model-item>

          <a-form-model-item label="券后价">
            <a-input v-model="form2.after_price" style="width: 200px">
              <span slot="addonAfter">元</span>
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="抵扣价">
            <a-input v-model="form2.zk_price" style="width: 200px">
              <span slot="addonAfter">元</span>
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="拍几件" prop="num">
            <a-input v-model="form2.num" style="width: 200px"> </a-input>
          </a-form-model-item>
          <a-form-model-item label="产品类型" prop="goods_type">
            <a-radio-group v-model="form2.goods_type">
              <a-radio :value="item.id" v-for="(item, index) in goodstype" :key="index">
                {{ item.name }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="佣金类型">
            <a-radio-group v-model="form2.commission_type">
              <a-radio :value="1">
                通用
              </a-radio>
              <a-radio :value="2">
                营销
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import EditorBar from '@/components/Editor/WangEditor'
import { getGoodsInfo, getGoodsType, stopGoods, shelfGoods, getClassInfo, updateGoodsInfo } from '@/api/goods'
export default {
  name: 'Productsmam',
  components: {
    EditorBar
  },
  data () {
    return {
      timearr: [],
      uploadurl: 'http://192.168.1.141:8088/api/upload',
      // uploadurl: 'http://tlj-api.letuilm.com/api/upload',
      confirmLoading: false,
      editgoods: false,
      dateFormat: 'YYYY/MM/DD',
      monthFormat: 'YYYY/MM',
      form: {
        page: 1,
        pagesize: 15,
        status: '1',
        item_id: '',
        search: '',
        start_time: '',
        end_time: '',
        goods_status: ''
      },
      columns: [
        {
          title: 'ID',
          dataIndex: 'item_id',
          align: 'center',
          // sorter: true,
          // width: '20%',
          scopedSlots: {
            customRender: 'item_id'
          }
        },
        {
          title: '产品名称',
          align: 'center',
          // dataIndex: 'goods_title',
          // width: '20%',
          scopedSlots: {
            customRender: 'goods_title'
          }
        },
        {
          title: '推广标题',
          dataIndex: 'tg_title',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'tg_title'
          }
        },
        {
          title: '图片',
          // dataIndex: 'goods_img',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'goods_img'
          }
        },
        {
          title: '优惠劵剩余/优惠卷总量',
          // dataIndex: 'coupon_surplus',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'coupon_surplus'
          }
        },
        {
          title: '原价/券后价/抵扣价',
          // dataIndex: 'price',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'price'
          }
        },
        {
          title: '商品类型',
          // dataIndex: 'goods_type',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'goods_type'
          }
        },
        {
          title: '佣金率(%)',
          dataIndex: 'commission_bl',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'commission_bl'
          }
        },
        {
          title: '服务费',
          dataIndex: 'service_price',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'service_price'
          }
        },
        {
          title: '服务费比例',
          // dataIndex: 'service',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'service'
          }
        },
        {
          title: '状态',
          // dataIndex: 'status',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'status'
          }
        },
        {
          title: '发布人',
          dataIndex: 'user_name',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'user_name'
          }
        },
        {
          title: '发布时间',
          dataIndex: 'create_at',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'create_at'
          }
        },
        {
          title: '活动结束时间',
          dataIndex: 'activity_end_time',
          // width: '20%',
          align: 'center',
          scopedSlots: {
            customRender: 'activity_end_time'
          }
        },
        {
          title: '操作',
          // dataIndex: 'active',
          // width: '20%',
          scopedSlots: {
            customRender: 'active'
          }
        }
      ],
      selectedRowKeys: [], // Check here to configure the default column
      data: [
        //   {
        //     after_price: '609.00',
        //     commission_bl: '12',
        //     coupon_num: 10000,
        //     coupon_surplus: 10000,
        //     coupon_url: 'https://uland.taobao.com/quan/detail?sellerId=725677994&activityId=75bc83cf8948471382a8c9604f323c0a',
        //     goods_img: '//img.letuilm.com/2020/08/bcd6e82020082717400312420.jpeg',
        //     goods_title: 'Ducky吉利鸭原魔力鸭One2 机械键盘樱桃红轴电竞游戏办公电脑背光',
        //     goods_type: 1,
        //     id: 8,
        //     item_id: '606540358182',
        //     month_num: 283,
        //     price: '629.00',
        //     service: '1',
        //     service_price: 298.41,
        //     tg_title: '测试提交',
        //     user_name: '陈柯帆',
        //     zk_price: '603.00'
        // }
      ],
      pagination: {},
      loading: false,
      typeList: [],
      uploadloading: false,
      imageUrl: '',
      labelCol: {
        span: 4
      },
      wrapperCol: {
        span: 12
      },
      classList: [
        // {
        //   id: 1,
        //   name: '其他'
        // }
      ],
      goodstype: [
        // {
        //   id: 1,
        //   name: '7元档(6元抵扣)'
        // }
      ],
      form2: {
        item_id: '',
        goods_url: '',
        goods_title: '',
        tg_title: '',
        goods_class: '',
        shop_name: '',
        shop_id: '',
        goods_img: '',
        month_num: '', // 月销量
        friend_text: '',
        coupon_url: '',
        activity_start_time: '',
        activity_end_time: '',
        coupon_num: '',
        coupon_surplus: '',
        single_sum: '',
        coupon_money: '',
        num: '',
        price: '',
        after_price: '',
        zk_price: '',
        target_num: '',
        goods_type: '1',
        commission_type: '1',
        commission_bl: '',
        service: ''
      },
      end_time: '',
      rules: {
        goods_url: [
          {
            required: true,
            message: '请输入淘宝产品链接!',
            trigger: 'blur'
          }
        ],
        goods_title: [
          {
            required: true,
            message: '请输入产品标题!',
            trigger: 'blur'
          }
        ],
        goods_img: [
          {
            required: true,
            message: '请上传商品图片!',
            trigger: 'blur'
          }
        ],
        friend_text: [
          {
            required: true,
            message: '请填写朋友圈文案!',
            trigger: 'blur'
          }
        ],
        coupon_url: [
          {
            required: true,
            message: '请输入优惠卷链接!',
            trigger: 'blur'
          }
        ],
        goods_type: [
          {
            required: true,
            message: '请选择商品类型!',
            trigger: 'change'
          }
        ],
        num: [
          {
            required: true,
            message: '请输入需要拍几件!',
            trigger: 'blur'
          }
        ],
        activity_start_time: [
          {
            required: true,
            message: '请选择开始和结束时间!',
            trigger: 'blur'
          }
        ],
        activity_end_time: [
          {
            required: true,
            message: '请选择开始和结束时间!',
            trigger: 'blur'
          }
        ],
        tg_title: [
          {
            required: true,
            message: '请输入推广标题!',
            trigger: 'blur'
          }
        ],
        goods_class: [
          {
            required: true,
            message: '请选择分类!',
            trigger: 'blur'
          }
        ],
        target_num: [
          {
            required: true,
            message: '请输入目标销量!',
            trigger: 'blur'
          }
        ],
        commission_bl: [
          {
            required: true,
            message: '请输入佣金率!',
            trigger: 'blur'
          }
        ],
        service: [
          {
            required: true,
            message: '请输入服务费率!',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  computed: {},
  created () {
    this.getGoodsType()
  },
  mounted () {},
  methods: {
    moment,
    doclear () {
      this.form = {
        page: 1,
        pagesize: 15,
        status: '1',
        item_id: '',
        search: '',
        start_time: '',
        end_time: '',
        goods_status: ''
      }
      this.timearr = []
    },
    open (item) {
      this.getClassInfo()
      this.form2 = item
      this.end_time = moment(this.form2.activity_end_time, 'YYYY-MM-DD')
      // console.log(this.form2.activity_end_time)
      this.editgoods = true
    },
    endChange () {
      console.log(this.end_time)
      //  this.form2.activity_end_time = parseInt(moment(this.end_time).valueOf() / 1000)
    },
    // 获取富文本内容
    getEditor (value) {
      // console.log(value)
      this.form2.friend_text = value
    },
    // 上传
    handleChange (info) {
      // console.log(info)
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.loading = false
        this.form2.goods_img = '//' + info.file.response.data.url
      }
    },
    closeimg () {
      this.form2.goods_img = ''
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('对不起!请上传jpg或者png格式的图片')
      }
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('对不起!图片大小不能超过5MB!')
      }
      return isJpgOrPng && isLt2M
    },
    // 获取分类
    getClassInfo () {
      getClassInfo()
        .then(res => {
          if (res.code === 200) {
            // console.log('分类返回', res)
            this.classList = res.data
          } else {
            this.$message.info(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 提交
    handleOk (e) {
      this.confirmLoading = true
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.form2.activity_end_time)
          this.form2.activity_end_time = parseInt(moment(this.end_time).valueOf() / 1000)
          updateGoodsInfo(this.form2)
            .then(res => {
              // console.log(res)
              if (res.code === 200) {
                this.getGoodsInfo()
                this.resetForm()
                this.form2 = {}
                this.editgoods = false
                this.$message.success('修改成功!')
                this.confirmLoading = false
              } else {
                this.$message.info(res.msg)
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },
    handleCancel (e) {
      this.editgoods = false
    },
    // 下架商品
    shelfGoods () {
      // console.log(this.selectedRowKeys)
      if (this.selectedRowKeys.length > 0) {
        var idstr = this.selectedRowKeys.toString()
        shelfGoods({
          id: idstr
        })
          .then(res => {
            if (res.code === 200) {
              // console.log('下架返回', res)
              this.$message.success('下架成功!')
            } else {
              this.$message.info(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.$message.info('请先勾选需要下架的商品之后再操作!')
      }
    },
    // 暂停商品
    stopGoods () {
      if (this.selectedRowKeys.length > 0) {
        var idstr = this.selectedRowKeys.toString()
        stopGoods({
          id: idstr
        })
          .then(res => {
            if (res.code === 200) {
              // console.log('暂停返回', res)
              this.$message.success('暂停成功!')
            } else {
              this.$message.info(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.$message.info('请先勾选需要暂停的商品之后再操作!')
      }
    },

    // 获取商品类型
    getGoodsType () {
      getGoodsType()
        .then(res => {
          if (res.code === 200) {
            this.getGoodsInfo()
            // console.log('返回', res)
            this.typeList = res.data
            this.goodstype = res.data
          } else {
            this.$message.info(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 获取自己的商品列表
    getGoodsInfo () {
      console.log(this.form)
      getGoodsInfo(this.form)
        .then(res => {
          if (res.code === 200) {
            console.log('自己的商品返回', res)
            this.data = res.data.data
            for (let i = 0; i < this.data.length; i++) {
              this.data[i].activity_end_time = moment(parseInt(this.data[i].activity_end_time + '000')).format(
                'YYYY-MM-DD HH:mm:ss'
              )
              // console.log(this.typeList)
              // 当前商品类型写死 只有一个 后期添加请修改typeList[0]
              if (this.typeList[0].id === this.data[i].goods_type) {
                this.data[0].typename = this.typeList[i].name
              }
            }
            const pagination = {
              ...this.pagination
            }
            pagination.total = res.data.count
            this.pagination = pagination
            // this.tabloading = false
          } else {
            this.$message.info(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange (pagination, filters, sorter) {
      // console.log(pagination)
      const pager = {
        ...this.pagination
      }
      pager.current = pagination.current
      this.pagination = pager
      this.fetch({
        results: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      })
    },
    fetch (params = {}) {
      console.log('params:', params)
      this.loading = true
      // some axaj
    },
    onChange (dates, dateStrings) {
      // console.log('From: ', dates[0], ', to: ', dates[1])
      // console.log('From: ', dateStrings[0], ', to: ', dateStrings[1])
      this.form.start_time = moment(dateStrings[0]).format('X')
      this.form.end_time = moment(dateStrings[1]).format('X')
    },
    callback () {
      console.log(this.form.status)
      if (this.form.status !== 1) {
        this.form.goods_status = ''
        console.log(this.form.goods_status)
      }
      this.getGoodsInfo()
    },
    selectchange () {
      console.log(this.form.goods_status)
    }
  }
}
</script>

<style lang="less" scoped>
.productsmam {
  width: 100%;

  .search_box {
    display: flex;
    justify-content: space-between;

    .search_left {
      width: 1230px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .btns {
    padding: 8px 0;
    float: right;
  }
}

.img_box {
  position: relative;
  width: 150px;
}

.anticon-close-circle {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 20px;
  cursor: pointer;
  display: none;
  z-index: 3;
  color: rgb(153, 153, 153);
  transition: all 0.3s linear;
}

.img_box:hover {
  .anticon-close-circle {
    display: block;
  }
}

.anticon-close-circle:hover {
  display: block;
  transform: rotate(90deg);
}
</style>
